package com.zy.imagineCommunity.controller;

import com.alibaba.fastjson.JSONObject;
import com.zy.imagineCommunity.entity.User;
import com.zy.imagineCommunity.service.UserSerivce;
import com.zy.imagineCommunity.util.MailClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
public class RegisterController {

    @Autowired
    private UserSerivce userSerivce;

    @Autowired
    private MailClient mailClient;

    //模板引擎注入进来即可用
    @Autowired
    private TemplateEngine templateEngine;

    //注入路径域名
    @Value("${ImagineCommunity.path.domain}")
    private String domain;

    //项目名
    @Value("${server.servlet.context-path}")
    private String contextPath;

    @RequestMapping(path = "/register", method = RequestMethod.GET)
    public String getRegister() {
        return "/register";
    }

    @ResponseBody
    @RequestMapping(path = "/register", method = RequestMethod.POST)
    public JSONObject register(String username, String email, String password) {

        User userByUsername = userSerivce.queryUserByUsername(username);

        User userByEmail = userSerivce.queryUserByEmail(email);

        JSONObject jsonObject = new JSONObject();

        if (userByUsername != null) {
            jsonObject.put("userByUsername", "yes");
            jsonObject.put("msg", "用户名已存在!");
            return jsonObject;
        }

        if (userByEmail != null) {
            jsonObject.put("userByEmail", "yes");
            jsonObject.put("msg", "邮箱已经被注册!");
            return jsonObject;
        }

        Date date = new Date();

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

        //对密码进行 md5 加密
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());

        userSerivce.addUser(new User(null, username, md5Password, email, "/ImagineCommunity/test/1615623293471.jpg", dateFormat.format(date), 0, "0_", 0));

        //下一步骤为激活邮件的部分
        User userByUsernameAndPassword = userSerivce.queryUserByUsernameAndPassword(username, md5Password);

        String url = domain + contextPath + "/activation/" + userByUsernameAndPassword.getId();
        System.out.println("url:" + url);
        //用Context构造模板
        Context context = new Context();
        //传入模板的变量存入Context对象
        context.setVariable("url", url);

        context.setVariable("email", email);
        //调整模板引擎成动态网页
        String content = templateEngine.process("mailActivation", context);
        //发送邮件
        mailClient.sendMail(email, "激活账号", content);

        jsonObject.put("registerSuccess", "yes");

        return jsonObject;
    }

    /**
     * 将id和方法从链接取得，用id查找用户并改变状态
     *
     * @param userId
     * @return
     */
    @RequestMapping(path = "/activation/{userId}", method = RequestMethod.GET)
    private String activation(@PathVariable("userId") int userId) {

        User user = userSerivce.queryUserByUserId(userId);

        userSerivce.updateUserByUserId(new User(user.getId(), user.getUsername(), user.getPassword(), user.getEmail(), user.getHeadImg(), user.getCreateTime(), 1, user.getLanguageState(), user.getMessageNum()));

        return "/login";
    }

    /**
     * 转到重置界面
     *
     * @return
     */
    @GetMapping("/resetPassword")
    public String getResetPassword() {
        return "/ResetPassword";
    }

    /**
     * 将要用于重置的信息通过邮件发送
     *
     * @param username
     * @param email
     * @param password
     * @return
     */
    @ResponseBody
    @PostMapping("/resetPassword")
    public JSONObject resetPassword(String username, String email, String password) {

        User userByEmail = userSerivce.queryUserByEmail(email);

        JSONObject jsonObject = new JSONObject();

        if (userByEmail == null) {
            jsonObject.put("userByEmail", "no");
            jsonObject.put("msg", "此邮箱还没有注册账号哦!");
            return jsonObject;
        }

        //下一步骤为激活邮件的部分
        String url = domain + contextPath + "/activationTwo/" + username + "/" + email + "/" + password;

        //用Context构造模板
        Context context = new Context();

        //传入模板的变量存入Context对象
        context.setVariable("url", url);

        context.setVariable("email", email);
        //调整模板引擎成动态网页
        String content = templateEngine.process("mailActivationTwo", context);
        //发送邮件
        mailClient.sendMail(email, "重置账号", content);

        jsonObject.put("resetPasswordSuccess", "yes");

        return jsonObject;
    }

    /**
     * 将username、email、password和方法从链接取得，用id查找用户并改变状态
     *
     * @param username
     * @param email
     * @param password
     * @return
     */
    @GetMapping("/activationTwo/{username}/{email}/{password}")
    private String activationTwo(@PathVariable("username") String username, @PathVariable("email") String email, @PathVariable("password") String password) {

        User user = userSerivce.queryUserByEmail(email);

        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());

        userSerivce.updateUserByUserId(new User(user.getId(), username, md5Password, user.getEmail(), user.getHeadImg(), user.getCreateTime(), user.getUserStatus(), user.getLanguageState(), user.getMessageNum()));

        return "/login";
    }

}
